﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;

public class GameUI : MonoBehaviour
{
    public Character character;

    private UserModel user;
    private GameModel game;

    private Text TextName { get; set; }
    private Text TextLevel { get; set; }
    private Text TextGold { get; set; }
    private Text TextOwl { get; set; }

    private Slider SliderHealth { get; set; }

    private Button BtnJump { get; set; }
    private GameObject JumpText { get; set; }
    private GameObject JumpAdd { get; set; }

    private Button BtnKey { get; set; }
    private GameObject KeyText { get; set; }
    private GameObject KeyAdd { get; set; }

    private Button BtnSuccess { get; set; }

    private bool JumpLock = true;
    private bool KeyLock = true;

    private int keyCount = 0;
    private bool canKey = false;

    private bool success = false;
    private GameObject cage = null;
    void Awake()
    {
        game = new GameModel();
        user = Engine.GameSystem.ReadUser();
        EventManager.AddListener(DataType.GetCharacter, GetCharacter);
        EventManager.AddListener(GameUI.DataType.GameOver, GameOver);
        EventManager.AddListener(DataType.Gold, AddGold);
        EventManager.AddListener(DataType.Owl, AddOwl);
        EventManager.AddListener(DataType.OnKey, OnKey);

        TextName = transform.FindChild("User/TextName").GetComponent<Text>();
        TextLevel = transform.FindChild("User/TextLevel").GetComponent<Text>();
        TextGold = transform.FindChild("Assets/ImageGold/TextValue").GetComponent<Text>();
        TextOwl = transform.FindChild("Assets/ImageOwl/TextValue").GetComponent<Text>();
        SliderHealth = transform.FindChild("User/SliderHealth").GetComponent<Slider>();

        BtnJump = transform.FindChild("ButtonJump").GetComponent<Button>();
        JumpText = transform.FindChild("ButtonJump/Jump").gameObject;
        JumpAdd = transform.FindChild("ButtonJump/Image").gameObject;

        BtnKey = transform.FindChild("ButtonKey").GetComponent<Button>();
        KeyText = transform.FindChild("ButtonKey/Key").gameObject;
        KeyAdd = transform.FindChild("ButtonKey/Image").gameObject;

        BtnSuccess = transform.FindChild("ButtonSuccess").GetComponent<Button>();

        TextName.text = user.userName;
        TextLevel.text = user.level.ToString();
        TextGold.text = game.gold.ToString();
        TextOwl.text = game.owl.ToString();
    }

    void Start()
    {
        EventManager.PostEvent(TipSystem.DataType.ShowTimeTip, "任务：收集金币，拯救至少2只猫头鹰。 任务提示：通过金币购买技能与钥匙拯救猫头鹰。", 1.6f);
    }
	
	void Update()
    {
        if (game.owl >= 2 && !success)
        {
            BtnSuccess.gameObject.SetActive(true);
        }
	}

    public void ButtonSuccess()
    {
        int reward_gold = game.gold;
        int reward_exp = (int)(game.gold * 0.8f) + game.owl * 25;
        int reward_crystal = game.owl == 3 ? 1 : 0;
        
        user.gold += reward_gold;
        user.exp += reward_exp;

        int levelTotalExp = 100 + (int)Math.Pow(user.level, 2) * 120;
        if (user.exp >= levelTotalExp)
        {
            user.level += 1;
            user.exp = user.exp - levelTotalExp;
        }

        user.crystal += reward_crystal;

        Engine.GameSystem.WriteUser(user);


        StageModel stage = Engine.GameSystem.ReadStage();
        stage.stage_02 = 1;

        Engine.GameSystem.WriteStage(stage);

        EventManager.PostEvent(TipSystem.DataType.ShowTimeTip, string.Format("恭喜过关，奖励：金币 {0}个 经验： {1}点 水晶 {2}块 解锁第二关卡", reward_gold, reward_exp, reward_crystal), 1.8f);

        //销毁界面并跳转到主界面
        DestroyGame("Stage01");
    }

    public void ButtonJump()
    {
        if (JumpLock)
        {
            if (game.gold >= 20)
            {
                game.gold -= 20;
                TextGold.text = game.gold.ToString();
                JumpAdd.SetActive(false);
                JumpText.SetActive(true);

                BtnKey.gameObject.SetActive(true);

                JumpLock = false;
            }
            else
            {
                EventManager.PostEvent(TipSystem.DataType.ShowTip, "还差" + (20 - game.gold).ToString() + "金币解锁跳跃技能");
            }
        }
        else
        {
            EventManager.PostEvent(Character.DataType.Jump);
        }
    }

    public void ButtonKey()
    {
        if (KeyLock && keyCount < 2)
        {
            if (game.gold >= 30)
            {
                game.gold -= 30;
                TextGold.text = game.gold.ToString();
                KeyAdd.SetActive(false);
                KeyText.SetActive(true);
                BtnKey.interactable = canKey;

                KeyLock = false;
            }
            else
            {
                EventManager.PostEvent(TipSystem.DataType.ShowTip, "还差" + (30 - game.gold).ToString() + "金币购买钥匙，用来拯救小猫头鹰");
            }
        }
        else
        {
            game.owl += 1;
            TextOwl.text = game.owl.ToString();
            keyCount++;

            if (cage != null)
            {
                cage.transform.Find("Cage").GetComponent<Animation>().Play();
                //GameObject.Destroy(cage);
                cage.GetComponent<SphereCollider>().isTrigger = false;
                canKey = false;
            }

            if (keyCount == 2)
            {
                BtnKey.gameObject.SetActive(false);
            }
            else
            {
                KeyLock = true;
                KeyAdd.SetActive(true);
                KeyText.SetActive(false);
                BtnKey.interactable = true;

            }
        }
    }

    public void OnKey(object[] parameters)
    {
        canKey = (bool)parameters[0];

        cage = canKey ? (GameObject)parameters[1] : null;

        if (!KeyLock)
        {
            BtnKey.interactable = canKey;
        }
    }

    private void DestroyGame(string name)
    {
        EventManager.RemoveListener(DataType.GetCharacter, GetCharacter);
        EventManager.RemoveListener(GameUI.DataType.GameOver, GameOver);
        EventManager.RemoveListener(DataType.Gold, AddGold);
        EventManager.RemoveListener(DataType.Owl, AddOwl);
        EventManager.RemoveListener(DataType.OnKey, OnKey);

        // 暂时把场景自销毁 以后放入StageManager
        Engine.GameSystem.UnLoad("System/InputSystem");
        Engine.GameSystem.UnLoad(name);
        Engine.UISystem.Next("Loading", "Home");
    }

    public void GameOver(object[] parameters)
    {
        if (character.character.health > 1)
        {
            character.transform.position = character.firstPos;
            character.character.health -= 1;
            SliderHealth.value = (float)character.character.health / (float)3;
        }
        else
        {
            EventManager.PostEvent(TipSystem.DataType.ShowTimeTip, "拯救失败，不给予任何奖励。", 1.6f);
            DestroyGame("Stage01");
        }
    }

    public void AddGold(object[] parameters)
    {
        int number = (int)parameters[0];
        game.gold += number;
        TextGold.text = game.gold.ToString();
    }

    public void AddOwl(object[] parameters)
    {
        int number = (int)parameters[0];
        game.owl += number;
        TextOwl.text = game.owl.ToString();
    }

    public void GetCharacter(object[] parameters)
    {
        character = (Character)parameters[0];
        SliderHealth.value = (float)character.character.health / (float)3;
    }

    public enum DataType
    {
        GetCharacter,
        Gold,
        Owl,
        OnKey,
        GameOver,
        GameSuccess
    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(50, 400, 150, 50), "增加金币"))
        {
            game.gold += 20;
            TextGold.text = game.gold.ToString();
        }

        if (GUI.Button(new Rect(50, 460, 150, 50), "通第二关"))
        {
            StageModel stage = Engine.GameSystem.ReadStage();
            stage.stage_03 = 1;

            Engine.GameSystem.WriteStage(stage);

            EventManager.PostEvent(TipSystem.DataType.ShowTimeTip, "恭喜过关，奖励：解锁第三关卡", 1.5f);

            DestroyGame("Stage02");
        }

        if (GUI.Button(new Rect(50, 520, 150, 50), "通第三关"))
        {
            StageModel stage = Engine.GameSystem.ReadStage();
            stage.stage_04 = 1;

            Engine.GameSystem.WriteStage(stage);

            EventManager.PostEvent(TipSystem.DataType.ShowTimeTip, "恭喜过关，奖励：解锁第四关卡", 1.5f);

            DestroyGame("Stage03");
        }

        if (GUI.Button(new Rect(50, 580, 150, 50), "通第四关"))
        {
            EventManager.PostEvent(TipSystem.DataType.ShowTimeTip, "恭喜全部过关", 1.5f);

            DestroyGame("Stage04");
        }

        if (GUI.Button(new Rect(50, 640, 150, 50), "重置数据"))
        {
            Engine.GameSystem.Reset();
        }

        if (GUI.Button(new Rect(50, 700, 150, 50), "退出游戏"))
        {
            Application.Quit();
        }
    }
}
